<script setup>
import { ref, computed ,reactive,onMounted} from 'vue'
import axios from "@/utils/axios.js"
import {client} from "@/utils/alioss.ts"
import {useUserStore} from "@/stores/user.js";

const users = useUserStore().user
const props = reactive({
  userData: {}
})

// 添加计算属性来处理手机号显示
const maskedPhone = computed(() => {
  if (!props.userData.phone || props.userData.phone.length !== 11) {
    return props.userData.phone
  }
  return props.userData.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
})

const saveChanges = () => {
  axios.post(`api/users/updateUsers`,props.userData)
      .then(res => {
        if (res.code === 200) {
          ElMessage({
            message: res.msg,
            type: 'success',
            duration:1500
          })
        }else{
          ElMessage({
            message: res.msg,
            type: 'warning',
            duration:1500
          })
        }
      })
}

const cancelChanges = () => {
  init()
}

onMounted(() => {
  init()
})

const us = JSON.parse(sessionStorage.getItem("user"));

const init = () => {
  axios.get(`/api/users/getUsers/${us.userId}`)
      .then(res => {
        props.userData = res.data
      })
}

//用户上传头像
const addForm = reactive({
  img:null,
  title:'',
  oriFileName:null,
})
const handleBeforeUpload = (file) =>{
  console.log("handleBeforeUpload");
  addForm.oriFileName = file.name;
  console.log(addForm.oriFileName);
  const isJPEG = file.name.split('.')[1] === 'jpeg';
  const isJPG = file.name.split('.')[1] === 'jpg';
  const isPNG = file.name.split('.')[1] === 'png';
  const isWEBP = file.name.split('.')[1] === 'webp';
  const isGIF = file.name.split('.')[1] === 'gif';
  const isLt500K = file.size / 1024 / 1024 / 1024 / 1024 < 4;
  if (!isJPG && !isJPEG && !isPNG && !isWEBP && !isGIF) {
    ElMessage({
      message: '上传图片只能是 JPEG/JPG/PNG 格式!',
      type: 'warning',
      plain: true,
    })
  }
  if (!isLt500K) {
    ElMessage({
      message: '单张图片大小不能超过 4mb!',
      type: 'warning',
      plain: true,
    })
  }
  return (isJPEG || isJPG || isPNG || isWEBP || isGIF) && isLt500K;
}
const uploadURL = (file) =>{
  console.log("uploadURL");
//注意哦，这里指定文件夹'image/'，尝试过写在配置文件，但是各种不行，写在这里就可以
  var fileName = 'abc/'+'banner' + `${Date.parse(new Date())}` +
      addForm.oriFileName;
//定义唯一的文件名，打印出来的uid其实就是时间戳
  client().put(fileName, file.file).
  then((res)=>{//此处赋值，是相当于上传成功之后，手动拼接服务器地址和文件名
    props.userData.avatar = res.url;
    console.log("这是url:"+props.userData.avatar)
  })
}

/*const changeAvatar=()=>{
  alert("sss")
}*/
</script>

<template>
  <van-nav-bar
      title="个人中心"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
      safe-area-inset-top
  />
  <div class="user-profile">
    <div class="profile-header">
      <div class="avatar-container">
        <el-image
            :src="props.userData.avatar"
            class="avatar-image"
            fit="cover"
        />
      </div>
      <div class="user-info">
        <div class="username-container">
          <br>
          <el-upload
              class="avatar-uploader"
              action=""
              v-model="addForm.img"
              :http-request="uploadURL"
              :before-upload="handleBeforeUpload"
              :limit="1"
          >
            <template #trigger>
              <el-button type="primary">更换头像</el-button>
            </template>
          </el-upload>
        </div>
      </div>
    </div>

    <div class="profile-form">
      <div class="form-item">
        <label>用户名</label>
        <input
            type="text"
            v-model="props.userData.username"
            placeholder="用户名需唯一"
            maxlength="20"
        />
        <div class="hint">4-20个字符</div>
      </div>

      <div class="form-item">
        <label>手机号</label>
        <input
            type="text"
            v-model="maskedPhone"
            placeholder="请输入手机号"
            readonly
        />

      </div>

      <div class="form-item">
        <label>性别</label>
        <div class="radio-group">
          <label class="radio-label">
            <input
                type="radio"
                value="male"
                v-model="props.userData.gender"
            />
            男
          </label>
          <label class="radio-label">
            <input
                type="radio"
                value="female"
                v-model="props.userData.gender"
            />
            女
          </label>
          <label class="radio-label">
            <input
                type="radio"
                value="保密"
                v-model="props.userData.gender"
            />
            保密
          </label>
        </div>
      </div>

      <div class="form-item">
        <label>个性签名</label>
        <textarea
            v-model="props.userData.signature"
            placeholder="请输入个性签名"
            maxlength="100"
        ></textarea>
        <div class="hint">最多100个字符 {{props.userData?.signature?.length || 0 }}/100</div>
      </div>

      <div class="form-item">
        <label>注册时间</label>
        <div class="readonly-field">{{ props.userData.createdAt}}</div>
      </div>

      <div class="form-item">
        <label>我的积分</label>
        <div class="readonly-field">{{ props.userData.points }}</div>
      </div>
    </div>

    <div class="action-buttons">
      <button class="save-btn" @click="saveChanges">保存修改</button>
      <button class="cancel-btn" @click="cancelChanges">取消</button>
    </div>
  </div>
</template>

<style scoped>
.avatar-container {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin-right: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(255, 149, 0, 0.3);
  border: 2px solid #ff9500;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.user-profile {
  background: white;
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.profile-header {
  display: flex;
  align-items: center;
  padding: 24px;
  background: linear-gradient(to right, #fff6e6, #ffedcc);
  border-bottom: 1px solid #ffe4b2;
}

.avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: #ff9500;
  margin-right: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(255, 149, 0, 0.3);
}

.user-info .username {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 6px;
  color: #333;
}

.membership {
  display: inline-block;
  padding: 4px 10px;
  background: #ff9500;
  color: white;
  border-radius: 12px;
  font-size: 12px;
}

.profile-form {
  padding: 24px;
}

.form-item {
  margin-bottom: 24px;
}

.form-item label {
  display: block;
  margin-bottom: 10px;
  font-weight: 600;
  color: #333;
  font-size: 15px;
}

.form-item input[type="text"],
.form-item textarea {
  width: 100%;
  padding: 14px;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  font-size: 15px;
  transition: all 0.3s;
}

.form-item input[type="text"]:focus,
.form-item textarea:focus {
  border-color: #ff9500;
  box-shadow: 0 0 0 2px rgba(255, 149, 0, 0.1);
  outline: none;
}

.form-item textarea {
  height: 90px;
  resize: vertical;
}

.radio-group {
  display: flex;
  gap: 24px;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-size: 15px;
}

.radio-label input[type="radio"] {
  width: 18px;
  height: 18px;
  accent-color: #ff9500;
}

.hint {
  font-size: 13px;
  color: #999;
  margin-top: 8px;
}

.readonly-field {
  padding: 14px;
  background: #f8f9fa;
  border-radius: 10px;
  color: #666;
  font-size: 15px;
}

.action-buttons {
  display: flex;
  gap: 16px;
  padding: 16px 24px 24px;
  background: #f8f9fa;
  border-top: 1px solid #eaeaea;
}

.save-btn {
  flex: 2;
  background: linear-gradient(to right, #ff9500, #ff8a00);
  color: white;
  border: none;
  padding: 16px;
  border-radius: 10px;
  cursor: pointer;
  font-weight: bold;
  font-size: 16px;
  box-shadow: 0 4px 10px rgba(255, 149, 0, 0.3);
  transition: all 0.2s;
}

.cancel-btn {
  flex: 1;
  background: #f1f1f1;
  color: #666;
  border: none;
  padding: 16px;
  border-radius: 10px;
  cursor: pointer;
  font-weight: bold;
  font-size: 16px;
  transition: all 0.2s;
}

.save-btn:hover {
  background: linear-gradient(to right, #ff8a00, #ff7a00);
  transform: translateY(-2px);
}

.cancel-btn:hover {
  background: #e5e5e5;
  transform: translateY(-2px);
}

.save-btn:active,
.cancel-btn:active {
  transform: translateY(0);
}

@media (max-width: 480px) {
  .user-profile {
    border-radius: 12px;
  }

  .profile-header {
    padding: 20px;
  }

  .avatar {
    width: 60px;
    height: 60px;
    font-size: 24px;
  }

  .profile-form {
    padding: 20px;
  }

  .action-buttons {
    padding: 12px 20px 20px;
  }
}
</style>